//
//  XMHomeView.m
//  XMJJ_zml
//
//  Created by apple on 2025/5/8.
//

#import "XMHomeView.h"
#import "RoundedSearchBar.h"
#import "CustomCollectionViewCell.h"
#import "ZMYTabBar.h"
#import "XMHomeMeetCell.h"

@interface XMHomeView ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ZMYTabBarDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) ZMYTabBar *topItemTabView;
@property (nonatomic, strong) UIButton *addressBtn;
@property (nonatomic, strong) UIButton *searchBgBtn;

@property (nonatomic, strong) NSMutableArray *dataArr;

@end

@implementation XMHomeView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
//    [self addSubview:self.navView];
//    self.navView.backgroundColor = kColorHEX(0xffffff);
    UIImageView *addressIcon = [[UIImageView alloc] initWithFrame:CGRectMake(KScaleWidth(16.0), kNavagationBarH - 44, KScaleWidth(12.0), 44)];
    addressIcon.contentMode = UIViewContentModeScaleAspectFit;
    addressIcon.image = ImageNamed(@"location");
    [self addSubview:addressIcon];
    
    UIButton *addressBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(14.0) frame:CGRectMake(addressIcon.maxX, addressIcon.y, KScaleWidth(52.0), 44) title:@"北京" titleColor:kColorHEX(0x221232) image:@"arrow"];
    [addressBtn layoutButtonWithEdgeInsetsStyle:CSButtonEdgeInsetsStyleRight ImageTitleSpace:KScaleWidth(7.0)];
    [addressBtn addTarget:self action:@selector(addressSelectAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:addressBtn];
    _addressBtn = addressBtn;
    
    UIButton *searchBgBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(13.0) frame:CGRectMake(KScaleWidth(88.0), kNavagationBarH - 44 + (44 - KScaleWidth(32.0))/2, self.width - KScaleWidth(88.0) - KScaleWidth(50.0), KScaleWidth(32.0)) title:@"输入搜索内容" titleColor:kColorHEX(0xCBC3D2) image:@"search"];
    searchBgBtn.backgroundColor = kColorHEX(0xF8F9FA);
    [searchBgBtn setCornerRadius:searchBgBtn.height/2];
    [searchBgBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [searchBgBtn setImageEdgeInsets:UIEdgeInsetsMake(0, KScaleWidth(10.0), 0, 0)];
    [searchBgBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, KScaleWidth(17.0), 0, 0)];
    [searchBgBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:searchBgBtn];
    _searchBgBtn = searchBgBtn;
    
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(14.0) frame:CGRectMake(self.width - KScaleWidth(8.0) - KScaleWidth(42.0), kNavagationBarH - 44, KScaleWidth(42.0), 44) title:@"搜索" titleColor:kColorHEX(0xCBC3D2)];
    [searchBtn addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:searchBtn];
    if (self.topItemTabView) {
        
    }
    [self addSubview:self.collectionView];
}

- (void)setContentWithMeetModelArr:(NSArray *)meetModelArr page:(NSInteger)page {
    [_collectionView.mj_header endRefreshing];
    if (page == 1) {
        [self.dataArr removeAllObjects];
    }
    if (meetModelArr.count < 10) {
        [_collectionView.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [_collectionView.mj_footer endRefreshing];
    }
    [self.dataArr addObjectsFromArray:meetModelArr];
    [_collectionView reloadData];
}

- (void)setLocation:(NSString *)cityName {
    CGFloat width = [cityName getWidthWithFont:KScaleWidth(14.0)] + KScaleWidth(20.0);
    XMWeakSelf;
    [UIView animateWithDuration:.3 animations:^{
        weakSelf.addressBtn.width = MAX(width, KScaleWidth(52.0));
        weakSelf.searchBgBtn.x = weakSelf.addressBtn.maxX + KScaleWidth(10.0);
        weakSelf.searchBgBtn.width = weakSelf.width - weakSelf.addressBtn.maxX - KScaleWidth(10.0) - KScaleWidth(50.0);
    }];
    [_addressBtn setTitle:cityName forState:UIControlStateNormal];
    [_addressBtn layoutButtonWithEdgeInsetsStyle:CSButtonEdgeInsetsStyleRight ImageTitleSpace:KScaleWidth(3.0)];
}

//地址选择
- (void)addressSelectAction:(UIButton *)button  {
    if (self.delegate && [self.delegate respondsToSelector:@selector(addressSelectAction)]) {
        [self.delegate addressSelectAction];
    }
}

//搜索
- (void)searchAction:(UIButton *)button {
    if (self.delegate && [self.delegate respondsToSelector:@selector(searchAction)]) {
        [self.delegate searchAction];
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat itemWidth = floor((self.width - KScaleWidth(8.0)*3)/2);
    ZMYCommend *zmyCommend = self.dataArr[indexPath.row];
    // 计算单行文本宽度
    NSString *text = zmyCommend.title;
    CGFloat height = [text getHeightWithFont:KScaleWidth(16.0) withWidth:itemWidth - KScaleWidth(10.0)*2] + KScaleWidth(10.0);
    return CGSizeMake(itemWidth, height + KScaleWidth(210.0) + KScaleWidth(74.0));
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XMHomeMeetCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XMHomeMeetCellName" forIndexPath:indexPath];
    [cell setContentWithMeetModel:self.dataArr[indexPath.row]];
//    cell.backgroundColor = [UIColor lightGrayColor]; // 这里用灰色背景代替实际图片
//    cell.data = self.dataArr[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    ZMYCommend *commend  = self.dataArr[indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(checkDetailWithProdId:)]) {
        [self.delegate checkDetailWithProdId:commend.objectId];
    }
//    XMHomeDetailViewController * detailVc = [XMHomeDetailViewController new];
//    detailVc.serviceId = commend.id;
//    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void)ZMYTabBar:(ZMYTabBar *)tabBar didSelectTabAtIndex:(NSInteger)index {
    if (self.delegate && [self.delegate respondsToSelector:@selector(tabSelectWithIndex:)]) {
        [self.delegate tabSelectWithIndex:index];
    }
}

#pragma mark - WaterfallFlowLayoutDelegate

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout*)collectionViewLayout
 heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZMYCommend *zmyCommend = self.dataArr[indexPath.item];
    // 计算单行文本宽度
    NSString *text = zmyCommend.title;
    UIFont *font = [UIFont systemFontOfSize:15.0];
    // 计算多行文本高度
    CGSize maxSize = CGSizeMake(300, CGFLOAT_MAX);
    CGRect rect = [text boundingRectWithSize:maxSize
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName: font}
                                     context:nil];
    CGFloat height = rect.size.height;
    
    return 200 + height + 100; // 默认占位尺寸
}

#pragma mark - Init
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = KScaleWidth(8.0);
        layout.minimumInteritemSpacing = KScaleWidth(8.0);
        layout.sectionInset = UIEdgeInsetsMake(KScaleWidth(8.0), KScaleWidth(8.0), KScaleWidth(8.0), KScaleWidth(8.0));
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, kNavagationBarH + KScaleWidth(47.0), self.width, self.height - KScaleWidth(47.0) - kNavagationBarH) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = kColorHEX(0xF6F6F6);
        [_collectionView registerClass:[XMHomeMeetCell class] forCellWithReuseIdentifier:@"XMHomeMeetCellName"];
        XMWeakSelf;
        _collectionView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(refreshData)]) {
                [weakSelf.delegate refreshData];
            }
        }];
        _collectionView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(loadMore)]) {
                [weakSelf.delegate loadMore];
            }
        }];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (ZMYTabBar *)topItemTabView {
    if (!_topItemTabView) {
        //    NSArray *tabTitles = @[@"推荐", @"关注", @"同城",@"新发布"];
        NSArray *tabTitles = @[@"关注", @"推荐", @"附近", @"新发布"];
        
        UIView * outSizeView = [[UIView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, KScaleWidth(47))];
        outSizeView.backgroundColor = [UIColor whiteColor];
        [self addSubview:outSizeView];
        
        _topItemTabView = [[ZMYTabBar alloc] initWithFrame:CGRectMake(KScaleWidth(60), 0, self.width - KScaleWidth(100.0), KScaleWidth(47)) titles:tabTitles];
        _topItemTabView.delegate = self;
        [_topItemTabView selectTabAtIndex:1 animated:YES];
        [outSizeView addSubview:_topItemTabView];
    }
    return _topItemTabView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
